<template>
  <view class="common-layout">
    <el-main class="el-main">
      <!-- 帖子列表 -->
      <PostList 
        :posts="posts" 
        :loading="loading"
        @view-detail="showDetail"
        @refresh="fetchPosts"
      />
      
      <SideBarInfo/>
      
      <!-- 帖子详情弹窗 -->
      <PostDetail
        :show="showDetailIsPop"
        :post="currentPost"
        :loading="detailLoading"
        @close="showDetailIsPop = false"
        @submit-comment="handleCommentSubmit"
        @like="handleLike"
      />
      
      <!-- 创建帖子弹窗 -->
      <CreatePost
        :show="showCreatePost"
        @close="showCreatePost = false"
        @submit="handleNewPost"
      />
      
      <!-- 悬浮发布按钮 -->
      <button class="float-create-btn" @click="showCreatePost = true">
        <i class="bi bi-pencil-square"></i>
      </button>
    </el-main>
  </view>
</template>

<script>
import { ref } from 'vue';
import PostList from '@/component/PostList.vue';
import PostDetail from '@/component/PostDetail.vue';
import SideBarInfo from '@/component/SideBarInfo.vue';
import CreatePost from '@/component/CreatePost.vue';
import api from '@/util/requestPost.js'; // 使用新的API结构

export default {
  components: {
    PostList,
    PostDetail,
    SideBarInfo,
    CreatePost
  },
  data() {
    return {
      posts: [],
      currentPost: null,
      loading: false,
      detailLoading: false,
      showDetailIsPop: false,
      showCreatePost: false,
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  created() {
    this.fetchPosts();
  },
  methods: {
    // 获取帖子列表（带分页）
    async fetchPosts() {
      if (this.loading) return;
      
      this.loading = true;
      try {
        const { list, pagination } = await api.postApi.getPostList({
          page: this.pagination.page,
          pageSize: this.pagination.pageSize
        });
        
        this.posts = list;
        this.pagination = {
          ...this.pagination,
          total: pagination.total,
          page: pagination.page
        };
      } catch (error) {
        console.error('获取帖子列表失败:', error);
        this.posts = [];
        uni.showToast({ 
          title: error.message || '加载失败', 
          icon: 'none' 
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 获取帖子详情
    async showDetail(postId) {
      this.showDetailIsPop = true;
      this.detailLoading = true;
      this.currentPost = {};
      
      try {
        this.currentPost = await api.postApi.getPostDetail(postId);
		console.log(this.currentPost);
      } catch (error) {
        console.error('获取帖子详情失败:', error);
        uni.showToast({
          title: error.message || '加载详情失败',
          icon: 'none'
        });
        this.showDetailIsPop = false;
      } finally {
        this.detailLoading = false;
      }
    },
		
    // 处理新建帖子
    async handleNewPost(postData) {
      try {
        
        // 1. 提交新帖子
        const createRes = await api.postApi.createPost({
          title: postData.title,
          content: postData.content,
          userId: postData.userId
        })
        console.log(createRes)
        if (!createRes) {
          throw new Error(createRes.msg || '发布失败')
        }
        
        uni.showToast({ title: '发布成功', icon: 'success' })
        
        // 2. 刷新帖子列表
        await this.fetchPosts()
        
        // 3. 关闭弹窗
        this.showCreatePost = false
        
      } catch (error) {
        console.error('发布失败:', error)
        uni.showToast({ 
          title: error.message || '发布失败', 
          icon: 'none' 
        })
      } finally {
      }
    },
	
    // 处理新建帖子
    async handleCommentSubmit(comment) {
      try {
        // 1. 使用Vue.set或this.$set确保响应式
        this.$set(this.currentPost, 'comments', this.currentPost.comments || []);
        
        // 2. 创建响应式评论对象
        const newComment = this.$set({}, 'comment', {
		  user_id: 0,
          commentId: Date.now(), // 临时ID
          postId: this.currentPost.post.postId,
          content: comment,
          likeCount: 0,
          createTime: new Date().toISOString()
        });
    
        // 3. 添加到数组（会自动触发更新）
        this.currentPost.comments.unshift(newComment);
    
        // 4. 提交到后端
        const { data } = await api.commentApi.createComment({
          postId: this.currentPost.post.postId,
          content: comment
        });
    
        // 5. 替换临时评论为真实数据
        const index = this.currentPost.comments.findIndex(c => c.commentId === newComment.commentId);
        if (index !== -1) {
          this.$set(this.currentPost.comments, index, {
            ...data,
            content: comment // 保留用户原始输入
          });
        }
      } catch (error) {
        // 失败时移除临时评论
        this.currentPost.comments = this.currentPost.comments.filter(c => c.commentId !== newComment.commentId);
      }
    },
    
    // 处理评论提交
    async handleCommentSubmit(comment) {
      // 1. 生成临时ID
      const tempId = 'temp_' + Date.now();
      
      // 2. 创建响应式评论对象
      const newComment = {
        commentId: tempId,
        postId: this.currentPost.post.postId,
        content: comment,
        likeCount: 0,
        create_time: new Date().toISOString(),
        _isTemp: true
      };
    
      // 3. 确保comments是响应式数组
      if (!Array.isArray(this.currentPost.comments)) {
        this.$set(this.currentPost, 'comments', []);
      }
    
      // 4. 插入到列表（触发视图更新）
      this.currentPost.comments.unshift(newComment);
    
      try {
        // 5. 提交到后端
        const { data } = await api.commentApi.createComment({
          postId: this.currentPost.post.postId,
          content: comment
        });
    
        // 6. 替换临时数据
        const index = this.currentPost.comments.findIndex(c => c._isTemp);
        if (index !== -1) {
          this.$set(this.currentPost.comments, index, {
            ...data,
            // 保留可能需要的临时字段
            content: comment 
          });
        }
      } catch (error) {
        // 7. 失败时移除临时评论
        this.currentPost.comments = this.currentPost.comments.filter(c => !c._isTemp);
        uni.showToast({ title: '发送失败', icon: 'none' });
      }
    },
    
    // 处理点赞
	async handleLike({ postId, isLike }) {
	  try {
		const res = await api.postApi.likePost(postId, isLike);
		
		// 强制更新视图（关键修复）
		// this.$set(this.currentPost.post, 'likeCount', this.currentPost.post.likeCount+1);

		
		return res;
	  } catch (error) {
		console.error('点赞失败:', error);
		throw error; // 继续抛出给子组件
	  }
	}
  }
};
</script>



<style>
@import url('https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css');
.common-layout{
	background-color: #ebf0f6;	
}

.el-main{
	display: flex;
	height: 88vh;
	border-radius: 10px;
}



.showDetailLable{
	width: 45px;
	height: 45px;
	border-radius: 50%;
	background-color: #fff;
	
}


.views-second{
	display: flex;
	justify-content: center;
	align-items: center;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 180px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
}

/* 添加帖子 */
.float-create-btn {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 56px;
  height: 56px;
  background-color: #5f8dee;
  color: white;
  border: none;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  box-shadow: 0 4px 12px rgba(95, 141, 238, 0.3);
  z-index: 99;
  transition: all 0.3s;
}

.float-create-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 6px rgba(95, 141, 238, 0.4);
}

/* 弹窗层级调整 */
.create-post-modal {
  z-index: 1001 !important;
}

.modal-mask {
  z-index: 1000 !important;
}
</style>
